#include "DbPart.h"
#include "connectpool.h"
#include "Game.h"
#include "util.h"

char g_szSQL[2056]={0};
#define MAX_SQL_BUF_LEN (sizeof(g_szSQL)-1)

CDbPart::CDbPart():m_dbHandler(NULL)
{
}

CDbPart::~CDbPart()
{
}


//表添加数据
void CDbPart::TabelAddAgencyAccountData(uint32 uid, const std::string &agency, uint32 agency_id, const std::string username)
{
    std::string strTabelName = "agency_account_" + std::to_string(agency_id);
    //检查表是否存在不存在就创建
    if (m_setAgencyAccount.find(agency_id) == m_setAgencyAccount.end())
    {
		if (CreateAgentcyAccountTabel(strTabelName))
		{
			m_setAgencyAccount.insert(agency_id);
		}
    }

    log_debug("TabelAddAgencyAccountData tabelname=%s", strTabelName.c_str());

    ostringstream ossSQL;
	ossSQL << "insert into " << strTabelName << "(uid, agency, agency_id, username, create_time) values(" << uid << ",\'" << agency << "\'," << agency_id << ",\'" << username << "\'," << CTools::GetUnixTime()<< ")";
	if (!m_dbHandler->UpdateSql(ossSQL.str().c_str()))
	{
		m_dbHandler->m_strError = m_dbHandler->m_pMysqlConn->What();
		log_error("TabelAddAgencyAccountData Error: %s\r Sql=%s \n", m_dbHandler->m_pMysqlConn->What().c_str(), ossSQL.str().c_str());
	}

    return;
}


//创建MYSQL表
bool CDbPart::CreateAgentcyAccountTabel(std::string& strTabelName)
{
    char cSql[] = "`  (\
        `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',\
        `uid` bigint(20) NOT NULL COMMENT '用户uid',\
        `agency_id` int(11) DEFAULT '0' COMMENT '用户代理id',\
        `agency` varchar(255) DEFAULT '0' COMMENT '用户代理',\
        `username` varchar(255) DEFAULT '0' COMMENT '用户名字(代理保持唯一)',\
		`create_time` bigint(20) UNSIGNED DEFAULT '0' COMMENT '创建时间',\
        PRIMARY KEY (`id`),\
        UNIQUE INDEX idx_uid (`uid`),\
        INDEX idx_username (`username`)\
        ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '代理商账号表' ROW_FORMAT = DYNAMIC;";

    memset(g_szSQL, 0, sizeof(g_szSQL));
    std::string strsql = "";
    strsql.append("CREATE TABLE IF NOT EXISTS`");
    strsql.append(strTabelName.c_str());
    strsql.append(cSql);

    strcat(g_szSQL, strsql.c_str());
    bool ret = m_dbHandler->m_pStore->Query(g_szSQL);
    if (ret == false) {
        log_error("CreatorLogGameCircleTabel failed What=%s g_szSQL=%s", m_dbHandler->m_pMysqlConn->What().c_str(), g_szSQL);
        return false;
    }
   
    log_debug("CreatorLogGameCircleTabel creator tabel return");
    return true;
}